package com.framework.oauthclient.service;

import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.framework.common.domain.ResultData;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * 按spring默认的逻辑commence里面会调用doHandle方法
 * 此时重写后不能调用，否则会读取2次resp流。
 * 所以此处没有调用doHandle， 并且直接out.close(), 最终导致OauthExceptionTranslator方法无效。
 * @author zzg
 */
public class OauthAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        PrintWriter out = resp.getWriter();
        ResultData<String> respBean = ResultData.error(HttpStatus.HTTP_UNAUTHORIZED, e.getMessage());
        out.write(new ObjectMapper().writeValueAsString(respBean));
        out.flush();
        out.close();
    }
}
